package com.tonghl.juc.queue_study.code;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Created by tonghl
 *
 * 抢车位
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore=new Semaphore(3);//3个车位

        for (int i = 1; i <=6; i++) {//6部汽车
             new Thread(()->{
             try{
                 semaphore.acquire();
                 System.out.println(Thread.currentThread().getName()+"\t 抢到车位");
                 try{
                     TimeUnit.SECONDS.sleep(3);
                 }catch (InterruptedException e){
                 e.printStackTrace();
                 }
                 System.out.println(Thread.currentThread().getName()+"\t 停车3秒后离开");
             }catch (InterruptedException e){
              e.printStackTrace();
             }finally {
               semaphore.release();
             }
             },String.valueOf(i)).start();
        }
    }
}
